package com.itheima.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.AllArgsConstructor;
import lombok.Data;

import static com.aliyun.teautil.Common.toJSONString;

/**
 * 短信发送工具类
 */
@Data
@AllArgsConstructor
public class SMSUtils {
    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private String templateCode;
    private String endpoint;
    /**
     * 发送短信
     * @param templateCode 模板
     * @param phoneNumbers 手机号
     * @param code 参数
     */
    public void sendMessage(String templateCode,String phoneNumbers,String code) {

        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 配置 AccessKey Secret，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);

        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setSignName(signName)
                .setTemplateCode(templateCode).setTemplateParam("{\"code\":\"" + code + "\"}"); // TemplateParam为序列化后的JSON字符串

        Client client = null;
        try {
            client = new Client(config);
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            System.out.println(toJSONString(sendSmsResponse));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}